package com.obggtc.picture.config;

import com.obggtc.picture.security.CustomAuthenticationEntryPoint;
import com.obggtc.picture.security.JwtAuthenticationFilter;
import com.obggtc.picture.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security配置类
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter(jwtUtils);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 开启CORS支持
            .cors()
            .and()
            // 禁用CSRF
            .csrf()
                .disable()
            // 禁用Session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 配置认证入口点
            .exceptionHandling()
                .authenticationEntryPoint(customAuthenticationEntryPoint)
            .and()
            // 配置请求授权
            .authorizeRequests()
                // 允许登录接口匿名访问
                .antMatchers("/auth/login","/test/auth").permitAll()
                // 允许静态资源访问
                .antMatchers("/static/**").permitAll()
                // 如果需要，可以允许某些接口匿名访问
                // .antMatchers("/video/upload", "/image/uploadImg").permitAll()
                // 其他所有请求需要认证
                .anyRequest().authenticated()
            .and()
            // 添加JWT过滤器
            .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
} 